package org.warehouse.service;

import java.util.List;

import org.warehouse.dao.IGroupDao;
import org.warehouse.dao.impl.GroupDao;
import org.warehouse.entity.Group;
import org.warehouse.entity.Product;
import org.warehouse.util.Sort;
import org.warehouse.util.WarehouseConstants;

public class Service implements IService {
	
	private static IService instance;

	public static IService getInstance() {
		if (instance == null) {
			synchronized (Service.class) {
				if (instance == null) {
					instance = new Service();
				}
			}
		}
		return instance;
	}

	private IGroupDao groupDao = GroupDao.getInstance();
	
	@Override
    public List<Group> getGroups() {
	    return groupDao.getAll();
    }
	
	@Override
	public int getCountOfPages(int groupId) {
		int countOfPages = Math.round(groupDao.getCountOfProducts(groupId) / WarehouseConstants.REQUEST_LIMIT) + 1; 
	    return countOfPages;
	}

	@Override
    public List<Product> getProducts(int groupId, int currentPage, Sort sortByName, Sort sortByPrice, String lastSortColumnName) {
		if (currentPage > 0) {
			currentPage--;
		}
		int offset = WarehouseConstants.REQUEST_LIMIT * currentPage;
	    return groupDao.getProductsForPage(groupId, WarehouseConstants.REQUEST_LIMIT, offset, sortByName, sortByPrice, lastSortColumnName);
    }

}
